import time

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from autoTest_ecshop.utils.log_util import logger

class Base():
    def __init__(self,driver):
        self.driver =driver
    ##查找单个元素
    def find_element(self,locator):
        try:
            logger.info(f"查找元素{locator}")
            return WebDriverWait(self.driver,5).until(EC.visibility_of_element_located(locator))
        except Exception as e:
            logger.error(f"元素 {locator} 定位失败。失败原因是：\n {e}")

    ##查找多个元素
    def find_elements(self, locator):
        try:
            logger.info(f"查找元素{locator}")
            return WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located(locator))
        except Exception as e:
            logger.error(f"元素 {locator} 定位失败。失败原因是：\n {e}")

    ## 输入数据
    def input_data(self,locator,keywords):
        ###查找元素
        element = self.find_element(locator)
        ### 清空输入框内容
        element.clear()
        ### 输入数据
        logger.info(f"输入数据：{keywords}")
        element.send_keys(keywords)
    def clickBtn(self,locator):
        ### 查找元素
        button =self.find_element(locator)
        ### 点击按钮
        logger.info(f"点击按钮：{locator}")
        button.click()
        time.sleep(1)

    def switchAlert(self,keywords=None,text=True,action=True):
        try:
            ## 切换到警告框
            ### 输入信息
            alert =self.driver.switch_to.alert
            ### 如果客户传入了数据，就向警告框发送文本
            if keywords:
                alert.send_keys(keywords)
            ## 如果text为True，就获取警告框的文本内容
            if text:
                text =alert.text
            ### 根据action的值决定点击"确定"或"取消"
            if action:
                ### 点击确认按钮
                alert.accept()
            else:
                ## 点击取消按钮
                alert.dismiss()
            ### 最后如果有获取文本内容，就打印并返回该文本
            if text:
                logger.info(f"返回文本信息:{text}")
                return text
        ### 如果整个过程出现异常，捕获并打印错误信息
        except Exception as e:
            logger.error(f"警告框的操作失败，错误信息是：\n{e}")
    def get_text(self,locator):
        ### 查找元素
        element = self.find_element(locator)
        ### 获取文本信息
        text = element.text
        logger.info(f"获取到的文本信息是：{text}")
        return text


